package com.newlink.building.main.ui

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.Settings
import android.util.Log
import android.view.View
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import com.newlink.building.library_rino.ConnectionController
import com.google.android.material.snackbar.Snackbar
import com.newlink.building.common_base.base.NL_BaseMvpActivity
import com.newlink.building.common_base.event.CallCreateActionBean
import com.newlink.building.common_base.event.CallCreateBean
import com.newlink.building.common_base.event.MessageEvent
import com.newlink.building.common_base.event.TYPE_CALL_SEND_CREATE_CHANNEL_REQUEST_PROPERTY_ROOM_USER
import com.newlink.building.common_base.event.TYPE_CALL_SEND_CREATE_CHANNEL_RESULT_PROPERTY_ROOM_USER
import com.newlink.building.common_base.event.TokenVo
import com.newlink.building.common_base.ext.showToast
import com.newlink.building.common_base.model.bean.RoomData
import com.newlink.building.common_base.model.bean.RoomUserData
import com.newlink.building.common_base.utils.PermissionHelper
import com.newlink.building.common_base.widget.CustomMessageDialog
import com.newlink.building.common_base.widget.SpaceItemDecoration
import com.newlink.building.main.R
import com.newlink.building.main.adapter.Module_Main_RoomUserAdapter
import com.newlink.building.main.databinding.ActivityRoomUserBinding
import com.newlink.building.main.mvp.contract.Module_Main_RoomUserContract
import com.newlink.building.main.mvp.presenter.Module_Main_RoomUserPresenter
import com.newlink.building.NL_App.Companion.coreContext
import com.newlink.building.manager.Module_Phone_VoipController
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.linphone.core.Call
import org.linphone.core.Core
import org.linphone.core.CoreListenerStub

/**
 * Created by xiaodong on 2025/3/10.
 */
class Module_Main_RoomUserActivityNL : NL_BaseMvpActivity<Module_Main_RoomUserContract.View, Module_Main_RoomUserContract.Presenter>(),
    Module_Main_RoomUserContract.View {
    override fun createPresenter() = Module_Main_RoomUserPresenter()
    private lateinit var mBinding: ActivityRoomUserBinding
    private var mAdapter = Module_Main_RoomUserAdapter(mutableListOf())
    private var roomData: RoomData? = null
    private var mRoomUserData: RoomUserData? = null
    var localChannelName: String = ""
    var tokenVo: TokenVo? = null
    override fun attachLayoutRes(): View? {
        mBinding = ActivityRoomUserBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun initData() {
        try {
            roomData = intent.getSerializableExtra("mRoomData") as RoomData
            roomData?.let {
                mPresenter?.getRoomUserList(accessToken, it.id, "")
            }
        } catch (e: Exception) {
            Log.e("RoomUserActivity", "--------- $e")
        }

        mBinding.recyclerview.run {
            layoutManager = GridLayoutManager(context, 3)
            addItemDecoration(SpaceItemDecoration(context))
            adapter = mAdapter
        }

        mAdapter.setOnItemClickListener { adapter, view, position ->
            mRoomUserData = mAdapter.getItem(position)
            if (!PermissionHelper.required(this).hasPermission(Manifest.permission.RECORD_AUDIO)
            ) {
                checkAudioPermission()
            } else {
//                makeCall()
                sendCreateChannelEvent()
            }
        }
    }

    fun sendCreateChannelEvent() {
        if (Module_Phone_VoipController.get().isCallingState()) {
            showToast(getString(R.string.outgoing_call_not_invite_again))
            return
        }
        val sipMsgEvent = MessageEvent(
            TYPE_CALL_SEND_CREATE_CHANNEL_REQUEST_PROPERTY_ROOM_USER,
            CallCreateActionBean(aid = agoraId)
        )
        EventBus.getDefault().post(sipMsgEvent)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMsgReceived(event: MessageEvent) {
        when (event.msgType) {
            TYPE_CALL_SEND_CREATE_CHANNEL_RESULT_PROPERTY_ROOM_USER -> {
                val callCreateBean = event.msgContent as CallCreateBean?
                localChannelName = callCreateBean?.data?.rtcToken?.channelName.orEmpty()
                tokenVo = callCreateBean?.data
                makeCall()
            }
        }
    }

    private val coreListener = object : CoreListenerStub() {
        override fun onCallStateChanged(
            core: Core,
            call: Call,
            state: Call.State,
            message: String,
        ) {
            when (state) {
                /**
                 * 由于在coreContext里OutgoingInit时会确保清除ChannelName,家庭成员呼叫是自己创建的ChannelName需要重新设置一下
                 */
                Call.State.OutgoingProgress -> {
                    if (localChannelName.isNotEmpty()) {
                        ConnectionController.getInstance(this@Module_Main_RoomUserActivityNL)
                            .setRemoteChannelName(localChannelName)
                    }
                    if (tokenVo != null) {
                        ConnectionController.getInstance(this@Module_Main_RoomUserActivityNL)
                            .convert2AgoraUserToken(tokenVo, agoraId, agoraAppId)
                    }
                }

                else -> {}
            }
        }
    }


    override fun initView() {
        super.initView()
        mBinding.tittlebar.tvTitleBarCenter.text = ContextCompat.getString(this, R.string.room_info)
        mBinding.tvRoomNumber.text = roomData?.roomNo.orEmpty()
        mBinding.tvRoomName.text = roomData?.roomName.orEmpty()
        coreContext.core.addListener(coreListener)
        initCallErrorMessage()
    }

    override fun getRoomUserListSuccess(data: MutableList<RoomUserData>) {
        mAdapter.setNewInstance(data)
    }

    private fun checkAudioPermission() {
        val message = getString(
            R.string.common_permission_audio_message,
            getString(R.string.common_permission_to_setting),
            getString(R.string.common_permission_microphone)
        )
        CustomMessageDialog(this).setTitle(getString(R.string.common_permission_title))
            .setMessage(message)

            .setNegativeButton(
                getString(R.string.cancel_dialog_custom)
            ) { dialog ->
                dialog.dismiss()
                showToast(getString(R.string.common_permission_cancel_alert))
            }
            .setPositiveButton(
                getString(R.string.common_permission_to_setting)
            ) { dialog ->
                requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), 0)
                dialog.dismiss()
            }.show()
    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 0) {
            for (i in permissions.indices) {
                when (permissions[i]) {
                    Manifest.permission.RECORD_AUDIO -> if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        //给了权限
                        sendCreateChannelEvent()
                    } else {
                        if (ActivityCompat.shouldShowRequestPermissionRationale(
                                this,
                                Manifest.permission.RECORD_AUDIO
                            )
                        ) {
                            //拒绝
                            checkAudioPermission()
                        } else {
                            openAppSettings()
                        }
                    }
                }
            }
        }
    }

    private fun openAppSettings() {
        val intent = Intent()
        intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
        val uri = Uri.fromParts("package", this.packageName, null)
        intent.data = uri
        startActivity(intent)
    }

    private fun makeCall() {
        Module_Phone_VoipController.get().makeAudioCall(mRoomUserData?.aid.toString(), mRoomUserData?.name)
    }

    override fun onDestroy() {
        super.onDestroy()
        coreContext.core.removeListener(coreListener)
    }

    private fun initCallErrorMessage() {
        coreContext.callErrorMessageResourceId.observe(
            this
        ) {
            it.consume { message ->
                showSnackBar(message)
            }
        }
    }

    override fun showSnackBar(message: String) {
        Snackbar.make(findViewById(android.R.id.content), message, Snackbar.LENGTH_LONG).show()
    }

}